package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.admin.AdminFeign;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.admin.pojo.AdChannel;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ZYJ on 2021/6/9 23:03
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 计算热文章
     */
    @Override
    public void computeHotArticle() {
        //1.获取近五天的文章数据
            //五天前的当前时间
        String time = LocalDateTime.now().minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            //近五天的文章数据
        List<ApArticle> articleList = apArticleMapper.loadArticleListByDate(time);
        //2.得到文章的分值 封装vo
        List<HotArticleVo> hotArticleVoList = getHotArticleVoList(articleList);
        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVoList);

    }
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    // 为每一个频道缓存热点较高的30条文章
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult responseResult = adminFeign.selectAllChannel();
        if(responseResult.getCode() == 0){
            List<AdChannel> channelList = JSON.parseArray
                    (JSON.toJSONString(responseResult.getData()), AdChannel.class);
            //2 遍历频道列表，筛选当前频道下的文章
            for (AdChannel channel : channelList) {
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                        .filter(hotArticleVo -> hotArticleVo.getChannelId().intValue() == (channel.getId()))
                        .collect(Collectors.toList());
                sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId());
            }
            //  默认频道缓存   缓存所有文章中热度最高的前30条文章 存入redis
            sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);


        }

    }

    //给每一个频道做热点文章缓存
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String redisKey) {
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        redisTemplate.opsForValue().set(redisKey,JSON.toJSONString(hotArticleVos));
    }

    //得到文章的分值
    private List<HotArticleVo> getHotArticleVoList(List<ApArticle> articleList) {
        return  articleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            //计算文章分值算法
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());

    }
    //计算文章分值方法
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;
        //评论
        if (apArticle.getComment() != null ){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //收藏
        if (apArticle.getCollection() != null ){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        //点赞
        if (apArticle.getLikes() != null ){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //阅读
        if (apArticle.getViews() != null ){
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }

        return score;
    }
}
